import React, { Component } from "react";

class Child extends Component {
  state = {
    name1: "",
  };
  //WARNING! To be deprecated in React v17. Use new lifecycle static getDerivedStateFromProps instead.
  // 在初始化阶段，不会执行，只有在运行中阶段，props改变的时候才会执行
  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps", nextProps);
    // 操作下一个props，转换为state，也可以进行一些请求
    this.setState({ name1: nextProps.name.substring(0, 1).toUppercase });
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps);
    // if (nextProps.text === this.props.text) {
    //   return false;
    // }
    if (JSON.stringify(nextProps) === JSON.stringify(this.props)) {
      return false;
    }
    return true;
  }

  render() {
    console.log("---------inner render-----------");
    return <div>{this.props.text}</div>;
  }
}
export default class App extends Component {
  state = {
    name: "xiaoming",
  };
  //WARNING! To be deprecated in React v17. Use componentDidUpdate instead.
  componentWillUpdate(nextProps, nextState) {
    console.log(
      "componentWillUpdate",
      nextState,
      document.getElementById("testApp")
    );
  }
  // 在state或者props改变以后，要执行某些操作
  componentDidUpdate(prevProps, prevState) {
    console.log(
      "componentDidUpdate",
      prevState,
      document.getElementById("testApp")
    );
  }
  render() {
    return (
      <div>
        App
        <Child text={this.state.name} />
        <button onClick={() => this.setState({ name: "xiaozheng" })}>
          修改名称
        </button>
        <div id="testApp">{this.state.name}</div>
        <Child />
      </div>
    );
  }
}
